<script setup lang="ts">
import { ITodoItem } from '../types/data'
import { storeToRefs } from 'pinia'
import useStore from '../store'
import TodoItem from './TodoItem.vue'
import { nextTick, ref } from 'vue'
const { main } = useStore()
const { getTodos, delTodo, updateTodo, updateAllStatus } = main
const { list, mainRadioStaus } = storeToRefs(main)
const inputRef = ref<HTMLInputElement>()
const currentName = ref('填写修改内容')
const handleKeyUp = (e: KeyboardEvent) => {
  if (e.key === 'Escape') {
    handleBlur()
    return
  }
  if(e.key === 'Enter'){
    if(currentName.value.trim() === '') return alert('不能为空')
    updateTodo(props.item.id,'name',currentName.value)
    handleBlur()
  }
}
const handleChangeInput = (item: ITodoItem) => {
  updateTodo(item.id, 'done', !item.done)
}
const handleDbclick = () => {
  isEditing.value = true
  currentName.value = props.item.name
  nextTick(() => {
    inputRef.value?.focus()
  })
}
const handleBlur = () => {
  isEditing.value = false
}
const isEditing = ref(false)
const props = defineProps<{
  item: ITodoItem
}>()
</script>
<template>
  <li :class="{completed:item.done,editing:isEditing}">
    <div class="view">
      <input class="toggle" type="checkbox" :checked="item.done" @change="handleChangeInput(item)" />
      <label @dblclick="handleDbclick">{{item.name}}</label>
      <button class="destroy" @click="delTodo(item.id)"></button>
    </div>
    <input class="edit" ref="inputRef" @blur="handleBlur" v-model="currentName" @keyup="handleKeyUp" />
  </li>
</template>